import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';
// import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner';
import {QRScanner,QRScannerStatus} from "@ionic-native/qr-scanner";

@IonicPage()
@Component({
  selector: 'page-scan',
  templateUrl: 'scan.html',
})
export class ScanPage {

  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    public alertCtrl: AlertController,
    public qrScanner: QRScanner) {
  }

  ionViewDidEnter() {
    this.scanQRCode();
  }

  scanQRCode() {
  //   this.qrScanner.prepare()
  //     .then((status: QRScannerStatus) => {
  //       if (status.authorized) {
  //         window.document.querySelector('body').classList.add('transparent-body');
  //         let scanSub = this.qrScanner.scan().subscribe((text: string) => {
  //           let alert = this.alertCtrl.create({
  //             title: '二维码内容',
  //             subTitle: text,
  //             buttons: ['OK']
  //           });
  //           alert.present();
  //           scanSub.unsubscribe();
  //         });
  //
  //         this.qrScanner.show();
  //
  //       }
  //       else if (status.denied) {
  //         //提醒用户权限没有开
  //       }
  //       else {
  //
  //       }
  //     })
  //     // .catch((e: any) => console.error('Error :', e));

    this.qrScanner.prepare()
      .then((status: QRScannerStatus) => {
        if (status.authorized) {
          // camera permission was granted


          // start scanning
          let scanSub = this.qrScanner.scan().subscribe((text: string) => {
            console.log('Scanned something', text);

            this.qrScanner.hide(); // hide camera preview
            scanSub.unsubscribe(); // stop scanning
          });

          // show camera preview
          this.qrScanner.show();

          // wait for user to scan something, then the observable callback will be called

        } else if (status.denied) {
          // camera permission was permanently denied
          // you must use QRScanner.openSettings() method to guide the user to the settings page
          // then they can grant the permission from there
        } else {
          // permission was denied, but not permanently. You can ask for permission again at a later time.
        }
      })
      .catch((e: any) => console.log('Error is', e));
  }

}
